<?php


namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Admin\Traits\AdminTrait;
use App\Http\Requests\Admin\BaseRequest;
use App\Models\Admin\AdminGroupClient;
use App\Models\Admin\AdminGroupClientUser;
use App\Models\Admin\AdminRegion;
use App\Models\Admin\Company;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class GroupClientController extends AdminController
{
    use AdminTrait;

    //新增集团
    public function addGroupClient(BaseRequest $request)
    {
        $input=$request->only('name','remark','head','base_address','mobile','company_id_domain','company_ids');
        $rules=[
            'name'=>"required|unique:admin_group_client",
            'head'=>"required",
            'base_address'=>"required|integer|min:1",
            'mobile'=>"required|digits:11|unique:admin_group_client",
            'company_id_domain'=>[
                'required',
                Rule::exists('company','id')
                    ->where('group_client_id',0),
            ],
            'company_ids'=>'required',
        ];
        $validator = Validator::make($input,$rules,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $company_ids=$input['company_ids'];
        $company_ids_arr=explode(',',$company_ids);
        DB::beginTransaction();
        try {
            unset($input['company_ids']);
            $info=AdminGroupClient::create($input);
            Company::whereIn('id',$company_ids_arr)->update([
               'group_client_id'=>$info->id
            ]);
            AdminGroupClient::addLog($info->toArray(),[],1);
            //生成默认账号
            AdminGroupClientUser::create([
                'name'=>$input['head'],
                'account'=>'admin',
                'role_id'=>1,
                'password'=>Hash::make($input['mobile']),
                'status'=>1,
                'mobile'=>$input['mobile'],
                'group_client_id'=>$info->id,
            ]);
            DB::commit();
            return $this->success();
        }
        catch (\Exception $exception)
        {
            DB::rollBack();
            return $this->error();
        }
    }

    //编辑集团
    public function editGroupClient(BaseRequest $request)
    {
        $input=$request->only('id','name','remark','head','base_address','mobile','company_id_domain','company_ids');
        $rules=[
            'id'=>'required|exists:admin_group_client',
            'name'=>[
                'required',
                Rule::unique('admin_group_client','name')
                ->ignore($input['id']),
            ],
            'head'=>"required",
            'base_address'=>"required|integer|min:1",
            'mobile'=>[
                'required',
                'digits:11',
                Rule::unique('admin_group_client','mobile')
                    ->ignore($input['id']),
            ],
            'company_id_domain'=>[
                'required',
                Rule::exists('company','id')
                    ->where(function ($query) use($input)
                    {
                        $query->where('group_client_id',0)
                            ->orWhere('group_client_id',$input['id']);
                    })
            ],
            'company_ids'=>'required',
        ];
        $validator = Validator::make($input,$rules,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $company_ids=$input['company_ids'];
        $group_id=$input['id'];
        $company_ids_arr=explode(',',$company_ids);
        DB::beginTransaction();
        try {
            $info=AdminGroupClient::find($group_id);
            $perInfo = $info->getOriginal();//获取修改之前的字段
            $info->name=$input['name'];
            $info->base_address=$input['base_address']??0;
            $info->head=$input['head'];
            $info->mobile=$input['mobile'];
            $info->company_id_domain=$input['company_id_domain'];
            $info->remark=$input['remark'];
            $info->save();
            $nextInfo = $info->getChanges();//获取修改之后的字段
            AdminGroupClient::addLog($perInfo,$nextInfo,2);
            //先把集团原来的子公司去除
            Company::where('group_client_id',$group_id)->update([
                'group_client_id'=>0
            ]);
            Company::whereIn('id',$company_ids_arr)->update([
                'group_client_id'=>$info->id
            ]);
            DB::commit();
            return $this->success();
        }
        catch (\Exception $exception)
        {
            DB::rollBack();
            return $this->error();
        }
    }

    public function getCompanyListNoGroup(BaseRequest $request)
    {
        $input=$request->all();
        $rules=[
            'company_name'=>'string',
        ];
        $validator = Validator::make($input, $rules,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $input['no_group']=1;
        $list=Company::getListByName($input);
        $data=[
            'list'=>$list,
        ];
        return  $this->success($data);
    }

    //获取集团客户列表
    public function getGroupClientList(BaseRequest $request)
    {
        $input=$request->all();
        $validator = Validator::make($input, $this->vali_rules,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $this->getPageAndSize($input);
        $list=AdminGroupClient::getList($input,$this->skip,$this->size);
        $count=AdminGroupClient::getCount($input);
        return $this->success([
            'list'=>$list,
            'count'=>$count,
        ]);
    }

    //根据集团id获取集团的超级管理员列表
    public function getGroupClientAdminList(BaseRequest $request)
    {
        $input=$request->all();
        $rule=[
            'group_client_id'=>'required|exists:admin_group_client,id',
        ];
        $validator = Validator::make($input, $rule,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $input['role_id']=1;
        $list=AdminGroupClientUser::getList($input);
        return $this->success([
            'list'=>$list
        ]);
    }

    //修改集团客户的超级管理员密码
    public function changePasswordGroupAdmin(BaseRequest $request)
    {
        $input=$request->all();
        //过滤数据
        $rule=[
            'id'=>'required|exists:admin_group_client_user,id',
            'password'=>'required',
        ];
        $validator = Validator::make($input, $rule,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $user_id=$input['id'];
        $password=Hash::make($input['password']);
        DB::beginTransaction();
        try {
            $info=AdminGroupClientUser::find($user_id);
            $perInfo = $info->getOriginal();//获取修改之前的字段
            $info->password=$password;
            $info->save();
            $nextInfo = $info->getChanges();//获取修改之后的字段
            AdminGroupClientUser::addLog($perInfo,$nextInfo,6,__FUNCTION__);
            DB::commit();
            return $this->success();
        }
        catch (\Exception $exception)
        {
            DB::rollBack();
            return $this->error();
        }
    }

    //免密登陆集团客户
    public function loginGroupNoPass(BaseRequest $request)
    {
        $input=$request->all();
        //过滤数据
        $rule=[
            'id'=>'required|exists:admin_group_client_user,id',
            'group_client_id'=>'required|exists:admin_group_client,id',
        ];
        $validator = Validator::make($input, $rule,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $user_id=$input['id'];
        $group_client_id=$input['group_client_id'];
        $user=AdminGroupClientUser::where('group_client_id',$group_client_id)->where('id',$user_id)->first();
        if(!$user)  return $this->error(['-1','管理员不存在']);
        $com_info=AdminGroupClient::with([
            'companyDomain:id,domain_name'
        ])
            ->select('id','name','company_id_domain')
            ->find($group_client_id);
        if(!$com_info->companyDomain || !$com_info->companyDomain->domain_name ) return $this->error(['-1','子公司未设置域名']);
        $token=Auth::guard('group_client')->login($user,true);
        if(!$token) return $this->error(['-1','token获取失败']);
        AdminGroupClient::addLog($com_info->getOriginal(),[],6,__FUNCTION__);
        $domain_name_arr=explode(',',$com_info->companyDomain->domain_name);
        $url='http://'.$domain_name_arr[0].'/group';
        return $this->success([
            'url'=>$url,
            'token'=>'Bearer ' .$token,
        ]);
    }

    //获取集团客户详情
    public function groupClientDetail(BaseRequest $request)
    {
        $input=$request->all();
        //过滤数据
        $rule=[
            'id'=>'required|exists:admin_group_client,id',
        ];
        $validator = Validator::make($input, $rule,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $id=$input['id'];
        $info=AdminGroupClient::getDetail($id);
        $region_id=$info->base_address;
        $info->mername=$info->adminRegion->mername;
        unset($info->adminRegion);
        //获取省市区数据
        $path_list=AdminRegion::getPathListById($region_id);
        $active_pid=AdminRegion::getPathById($region_id);
        array_unshift($active_pid,$region_id);
        $info['active_pid']=array_reverse($active_pid);
        $info['path_list']=$path_list;
        return $this->success($info);

    }

}
